package com.byzk.p2p.admin.admin.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.byzk.p2p.admin.admin.dto.SysUser;
import com.byzk.p2p.admin.admin.service.AdminService;
import com.byzk.p2p.admin.admin.vo.AdminIndexShow;
import com.byzk.p2p.admin.admin.vo.AdminUserVo;
import com.byzk.p2p.admin.base.controller.AdminBaseController;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.util.SHA;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.group.dto.Group;
import com.byzk.p2p.admin.group.service.GroupService;
import com.byzk.p2p.admin.system.service.MenuService;
import com.byzk.p2p.admin.system.vo.MenuItem;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminController extends AdminBaseController {

	@Autowired
	private MenuService menuService;

	@Autowired
	private AdminService adminService;

	@Autowired
	private GroupService groupService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private TenderService tenderService;




	
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginView(Model model, @RequestParam(required = false) String error) {
		if (StringUtils.isNotEmpty(error)) {
			String msg = "";
			if ("1".equals(error)) {
				msg = "请输入验证码";
			}
			if ("2".equals(error)) {
				msg = "验证码有误";
			}
			if ("3".equals(error)) {
				msg = "用户不存在";
			}
			if ("4".equals(error)) {
				msg = "密码错误";
			}
			model.addAttribute("msg", msg);
		}
		
		return ftl(Thread.currentThread().getStackTrace());
	}

	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String loginSubmit(@ModelAttribute SysUser admin) throws Exception {
		if (StringUtils.isBlank(admin.getCode())) {
			return redirect("/admin/login?error=1");
		} else {
			if (!admin.getCode().equalsIgnoreCase((String) session.getAttribute("jcaptchaCode"))) {
				return redirect("/admin/login?error=2");
			}
		}

		AdminUserVo temp = adminService.getVoByName(admin.getUserName());
		if (temp == null) {
			return redirect("/admin/login?error=3");
		} else {
			if (!temp.getPassword().equals(SHA.encryptPassword(admin.getPassword()))) {
				return redirect("/admin/login?error=4");
			}
		}
		session.setAttribute("sysUser", temp);
		session.setMaxInactiveInterval(60*60*24);
		return redirect("/admin/index");
	}

	/**
	 * 添加管理员
	 * @param sysUser 后台管理员
	 * @throws Exception
	 */
	@RequestMapping(value="/user/save")
	public void addAdminUser(@RequestBody SysUser sysUser) throws Exception{
		if (StringUtils.isBlank(sysUser.getUserName())) {
			printJSON(new JsonMsg(1, "用户名不能为空！"));
			return;
		}
		if (StringUtils.isBlank(sysUser.getPassword())) {
			printJSON(new JsonMsg(1, "密码不能为空！"));
			return;
		}
		if (sysUser.getGroupId() == null) {
			printJSON(new JsonMsg(1, "用户组不能为空！"));
			return;
		}
		sysUser.setStatus("N");
		sysUser.setPassword(SHA.encryptPassword(sysUser.getPassword()));
		sysUser.setCreateTime(new Date());
		Integer i = adminService.saveOrUpdate(sysUser);
		if (i > 0) {
			printJSON(new JsonMsg(-1, "添加成功！"));
		}else{
			printJSON(new JsonMsg(1, "添加失败！"));
		}
	}
	
	@RequestMapping(value = "/password/update", method = RequestMethod.GET)
	public String updatePassword(){
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 修改后台用户密码
	 * @param oldPwd 旧密码
	 * @param newPwd 新密码
	 * @param confirmPassword 确认密码
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/password/update", method = RequestMethod.POST)
	public String setAdminUserPwd(@RequestParam("oldPwd") String oldPwd,
								  @RequestParam("newPwd") String newPwd,
								  @RequestParam("rePwd") String rePwd) throws Exception {
		AdminUserVo adminUserVo = (AdminUserVo)session.getAttribute("sysUser");
		if (adminUserVo == null) {
			printJSON(new JsonMsg(1, "请重新登录！"));
			return null;
		}
		if (StringUtils.isBlank(oldPwd)) {
			printJSON(new JsonMsg(2, "旧密码不能为空！"));
			return null;
		}
		SysUser sysUser = adminService.getByName(adminUserVo.getUserName());
		if (sysUser == null) {
			printJSON(new JsonMsg(3, "用户不存在！"));
			return null;
		}
		if (!sysUser.getPassword().equals(SHA.encryptPassword(oldPwd))) {
			printJSON(new JsonMsg(4, "旧密码错误，请重新输入！"));
			return null;
		}
		if (StringUtils.isBlank(newPwd)) {
			printJSON(new JsonMsg(5, "新密码不能为空！"));
			return null;
		}
		if (StringUtils.isBlank(rePwd)) {
			printJSON(new JsonMsg(6, "确认密码不能为空！"));
			return null;
		}
		if (!newPwd.equals(rePwd)) {
			printJSON(new JsonMsg(7, "新密码与确认密码不一致，请重新输入！"));
			return null;
		}

		sysUser.setPassword(SHA.encryptPassword(newPwd));
		Integer i = adminService.saveOrUpdate(sysUser);
		if (i > 0) {
			printJSON(new JsonMsg(-1, "修改成功！"));
			return null;
		}else{
			printJSON(new JsonMsg(1, "修改失败！"));
			return null;
		}
	}
	
	/**
	 * 后台注销
	 * @return
	 */
	@RequestMapping(value="/logout",method = RequestMethod.GET)
	public String logout(){
		session.removeAttribute("sysUser");
		session.removeAttribute("jcaptchaCode");
		return redirect("/admin/index");
	}
	
	@RequestMapping(value = { "/index", "/" }, method = RequestMethod.GET)
	public String indexView(Model model) {
		AdminUserVo admin = (AdminUserVo) session.getAttribute("sysUser");
		List<MenuItem> menus = null;
		if (admin == null) {
			return redirect("/admin/login");
		} else {
			if (admin.getGroupId() == 1) {
				menus = menuService.getMenusByGroupId(-1);
			} else {
				menus = menuService.getMenusByGroupId(admin.getGroupId());
			}
		}

		model.addAttribute("admin", admin);
		model.addAttribute("menus", menus);
		return ftl(Thread.currentThread().getStackTrace());
	}

	@RequestMapping(value = "/404", method = RequestMethod.GET)
	public String missPage() {
		return redirect("/index");
	}

	@RequestMapping(value = "/dash", method = RequestMethod.GET)
	public String dash(Model model) {
		AdminIndexShow adminIndexShow = new AdminIndexShow();
		Map<String, Object> pcTerminalMap = new HashMap<String, Object>();
		pcTerminalMap.put("terminal", "PC");
		Map<String, Object> wxTerminalMap = new HashMap<String, Object>();
		wxTerminalMap.put("terminal", "WX");
		Map<String, Object> appTerminalMap = new HashMap<String, Object>();
		appTerminalMap.put("terminal", "APP");
		adminIndexShow.setUserCount(userService.countAll());
		adminIndexShow.setPcUserCount(userService.countAll(pcTerminalMap));
		adminIndexShow.setAppUserCount(userService.countAll(appTerminalMap));
		adminIndexShow.setWxUserCount(userService.countAll(wxTerminalMap));
		adminIndexShow.setIncome(tenderService.getAllRecovedInterest() == null ? 0 : tenderService.getAllRecovedInterest());
		adminIndexShow.setTenderMoney(tenderService.getAllTenderAmount(null,null) == null ? 0 : tenderService.getAllTenderAmount(null,null));
		List<UserTender> userTenders = tenderService.getMonthTender(Integer.valueOf(new DateTime().toString("yyyy")));
		adminIndexShow.setUserTenders(userTenders);
		model.addAttribute("adminIndexShow", adminIndexShow);
		return ftl(Thread.currentThread().getStackTrace());
	}

	@RequestMapping("/list")
	public String listAdminUser(Model model,
			@RequestParam(value = "index", required = false, defaultValue = "1") int index,
			@RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {
		PageInfo<AdminUserVo> pageInfo = adminService.adminUserList(null, index, limit);
		model.addAttribute("pageInfo", pageInfo);
		// 获取所有的组
		List<Group> groups = groupService.getAllGroup();
		model.addAttribute("groups", groups);
		return ftl(Thread.currentThread().getStackTrace());
	}

	@RequestMapping("/settingUserGroup")
	public String settingUserGroup(Model model, @RequestParam Integer id) {
		SysUser sysUser = adminService.getSysUsersById(id);
		// 获取所有的组
		List<Group> groups = groupService.getAllGroup();
		model.addAttribute("groupId", sysUser.getGroupId());
		model.addAttribute("userId", id);
		model.addAttribute("groups", groups);
		return ftl(Thread.currentThread().getStackTrace());
	}

	@RequestMapping("/saveUserGroup")
	public void saveUserGroup(@RequestParam Integer uId, @RequestParam Integer gId) {
		SysUser sysUser = adminService.getSysUsersById(uId);
		if (sysUser != null) {
			sysUser.setGroupId(gId);
			try {
				Integer i = adminService.saveOrUpdate(sysUser);
				if (i > 0) {
					printJSON(new JsonMsg(-1, "操作成功"));
				} else {
					printJSON(new JsonMsg(0, "操作失败"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value="/sim/login",method=RequestMethod.POST)
	public void simLogin(@RequestParam Integer userId) throws Exception{
		User user = userService.getById(userId);
		if(user == null){
			printJSON(new JsonMsg(0, "模拟失败！"));
		}else{
			session.setAttribute("_user", user);
			printJSON(new JsonMsg(-1, "模拟成功！"));
		}
	}
}
